
Drupal.heartbeat = Drupal.heartbeat || {};

Drupal.heartbeat.polling = false;

Drupal.heartbeat.getOlderMessages = function(element) {
  $.post(element.href, {block: 1, ajax: 1}, Drupal.heartbeat.appendMessages);
}

Drupal.heartbeat.appendMessages = function(data) {
  var result = Drupal.parseJson(data);
  $('.heartbeat-older-messages').each(function(d){ $(this).remove(); });
  $('.heartbeat-messages-wrapper').append(result['data']);

  Drupal.attachBehaviors($('.heartbeat-stream'));
}

Drupal.heartbeat.prependMessages = function(data) {
  var result = Drupal.parseJson(data);
  
  // Append the messages
  $('.heartbeat-messages-wrapper').prepend(result['data']);
  
  // Update the times in the stream
  var time_updates = result['time_updates'];
  for (uaid in time_updates) {
    $('#beat-item-' + uaid).find('.heartbeat_times').text(time_updates[uaid]);
  }

  Drupal.attachBehaviors($('.heartbeat-stream'));
}

Drupal.heartbeat.pollMessages = function() {
  
  var href = Drupal.settings.basePath + 'heartbeat/js/poll';
    
  var stream = $('.heartbeat-stream').attr('id').replace("heartbeat-stream-", "");
  
  var first = true;
  var uaids = new Array();
  var firstUaid = 0;
  $('.heartbeat-stream .beat-item').each(function(i) {

    var uaid = parseInt($(this).attr('id').replace("beat-item-", ""));
    
    if (first) {
      firstUaid = uaid;
      first = false;
    }
    uaids.push(uaid);
  });
  
  if (firstUaid) {
    $.post(href, {latestUaid: firstUaid, stream: stream, uaids: uaids.join(',')}, Drupal.heartbeat.prependMessages);
  }
}

Drupal.behaviors.heartbeat = function (context) {  
  
  if (Drupal.settings.heartbeatPollNewerMessages && !Drupal.heartbeat.polling) {
    var interval = Drupal.settings.heartbeatPollNewerMessages * 1000;
    var poll = setInterval('Drupal.heartbeat.pollMessages()', interval);
    Drupal.heartbeat.polling = true;
  }
}